﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Dynamic;
using System.Reflection;

using Tango.Dynamic;
using Tango.Scripting;


namespace Tango.ExpressionCompiler.DynamicExpression.Binders
{
	class ArrayAccessBinder : BinderBase
	{
		public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args)
		{
			BindingRestrictions restrictions=BindingRestrictions.Empty;
			Expression expression=null;

			Expression instance=target.GetLimitedExpression();
			var indexes=args.Select(o=>o.GetLimitedExpression());

			ExpressionEx.TryArrayAccess(instance,indexes,out expression);
			if(expression!=null) 
			{
				expression=expression.ConvertTo(this.ReturnType);
			}
			else
			{
				expression=ThrowException("could not access array");
			}

			restrictions=restrictions.ForAll(target,args);
			return new DynamicMetaObject(expression,restrictions);
		}
	}
}
